package com.canyou.utils;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cd
 */
@Data
@Component
public class WordToPdf {

    @Value("${libreoffice.linuxPath}")
    private String linuxPath;

    @Value("${libreoffice.windowsPath}")
    private String windowsPath;

    @Value("${libreoffice.docToPdfPath}")
    private String docToPdfPath;

    public boolean exeCommand(String tempdir, String outPath) throws IOException {
        String officehome = linuxPath;

        // windows,linux
        String osName = System.getProperty("os.name");
        if (osName != null && osName.toLowerCase().contains("windows")
                && StrUtil.isNotBlank(windowsPath)) {
            officehome = windowsPath;
            if (tempdir.startsWith("/")) {
                tempdir = tempdir.substring(1, tempdir.length());
            }
            if (outPath.startsWith("/")) {
                outPath = outPath.substring(1, outPath.length());
            }
        }
        List<String> commands = new ArrayList<String>();
        commands.add(officehome + "/soffice");
        commands.add("--headless");
        commands.add("--invisible");
        commands.add("--convert-to");
        commands.add("pdf");
        commands.add(tempdir);
        commands.add("--outdir");
        commands.add(outPath);
        // soffice --headless --convert-to 目标格式（如pdf） 转格式文件 --outdir 目标文件夹
        // "soffice --headless --invisible --convert-to pdf " + tempdir + " --outdir "+ outPath;

        String exs = executeCommand(commands);
        if (exs == null || exs.length() <= 0) {
        } else {
            if (exs.indexOf("writer_pdf_Export") >= 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 执行LibreOffice或者Apache_OpenOffice 命令行，实现word转换Pdf
     *
     * @throws IOException
     **/
    private synchronized String executeCommand(List<String> commands) throws IOException {
        StringBuffer output = new StringBuffer();
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "UTF-8");

        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
        inputStreamReader = new InputStreamReader(process.getErrorStream(), "UTF-8");
        reader = new BufferedReader(inputStreamReader);
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
        reader.close();
        inputStreamReader.close();
        return output.toString();
    }

}
